<template>
  <div class="login-container">
    <h3 class="form-title">{{ isLoginMode ? '用户登录' : '用户注册' }}</h3>

    <!-- 登录表单 -->
    <el-form
      v-if="isLoginMode"
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      size="large"
      @keyup.enter="handleLogin"
    >
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="用户名"
          prefix-icon="User"
          clearable
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          placeholder="密码"
          prefix-icon="Lock"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          class="submit-button"
          @click="handleLogin"
        >
          登录
        </el-button>
      </el-form-item>

      <div class="form-footer">
        <span>没有账号?</span>
        <el-link type="primary" @click="toggleMode">立即注册</el-link>
      </div>

      <div class="role-demo">
        <p class="demo-title">演示账号:</p>
        <div class="role-buttons">
          <el-button size="small" @click="fillDemoAccount('farmer')">
            农户演示
          </el-button>
          <el-button size="small" @click="fillDemoAccount('buyer')">
            买家演示
          </el-button>
          <el-button size="small" @click="fillDemoAccount('seller')">
            肥料商演示
          </el-button>
        </div>
      </div>
    </el-form>

    <!-- 注册表单 -->
    <el-form
      v-else
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      size="large"
    >
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="用户名"
          prefix-icon="User"
          clearable
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          placeholder="密码"
          prefix-icon="Lock"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          placeholder="确认密码"
          prefix-icon="Lock"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item prop="name">
        <el-input
          v-model="registerForm.name"
          placeholder="姓名"
          prefix-icon="User"
          clearable
        />
      </el-form-item>

      <el-form-item prop="role">
        <el-select
          v-model="registerForm.role"
          placeholder="请选择角色"
          class="select-full-width"
        >
          <el-option label="农户" value="farmer" />
          <el-option label="农产品买家" value="buyer" />
          <el-option label="肥料卖家" value="seller" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          class="submit-button"
          @click="handleRegister"
        >
          注册
        </el-button>
      </el-form-item>

      <div class="form-footer">
        <span>已有账号?</span>
        <el-link type="primary" @click="toggleMode">立即登录</el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { useUserStore } from '../../store';

// 路由和状态管理
const router = useRouter();
const userStore = useUserStore();

// 表单模式控制
const isLoginMode = ref(true);
const loading = ref(false);
const rememberMe = ref(false);

// 表单引用
const loginFormRef = ref(null);
const registerFormRef = ref(null);

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
});

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  role: ''
});

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
  ]
};

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 切换登录/注册模式
function toggleMode() {
  isLoginMode.value = !isLoginMode.value;
}

// 处理登录
async function handleLogin() {
  if (!loginFormRef.value) return;

  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      loading.value = true;
      await userStore.login(loginForm);
      ElMessage.success('登录成功');
      router.push('/main/dashboard');
    } catch (error) {
      console.error('登录失败', error);
      ElMessage.error(error.message || '登录失败，请检查用户名和密码');
    } finally {
      loading.value = false;
    }
  });
}

// 处理注册
async function handleRegister() {
  if (!registerFormRef.value) return;

  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      loading.value = true;

      const userData = {
        username: registerForm.username,
        password: registerForm.password,
        nickname: registerForm.name,
        role: registerForm.role
      };

      await userStore.register(userData);
      ElMessage.success('注册成功，请登录');
      isLoginMode.value = true;

      // 填充刚注册的用户名，方便用户登录
      loginForm.username = registerForm.username;
      loginForm.password = '';
    } catch (error) {
      console.error('注册失败', error);
      ElMessage.error(error.message || '注册失败，用户名可能已存在');
    } finally {
      loading.value = false;
    }
  });
}

// 填充演示账号
function fillDemoAccount(role) {
  switch (role) {
    case 'farmer':
      loginForm.username = 'farmer1';
      loginForm.password = '123456';
      break;
    case 'buyer':
      loginForm.username = 'buyer1';
      loginForm.password = '123456';
      break;
    case 'seller':
      loginForm.username = 'seller1';
      loginForm.password = '123456';
      break;
  }
}

// 处理登出
function handleLogout() {
  userStore.logoutUser();
}
</script>

<style scoped>
.login-container {
  width: 100%;
}

.form-title {
  text-align: center;
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.submit-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.form-footer {
  margin-top: 16px;
  text-align: center;
}

.select-full-width {
  width: 100%;
}

.role-demo {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px dashed var(--el-border-color-light);
}

.demo-title {
  margin-bottom: 10px;
  text-align: center;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.role-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
